<?php 
/**
*
* example目录下为简单的支付样例，仅能用于搭建快速体验微信支付使用
* 样例的作用仅限于指导如何使用sdk，在安全上面仅做了简单处理， 复制使用样例代码时请慎重
* 请勿直接直接使用样例对外提供服务
* 
**/
namespace App\Tools;

class WechatPay{

    public function Getcode()
    {
        //通过code获得openid
        if (!isset($_GET['code'])){
            $baseUrl = urlencode('https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
            //触发微信返回code码
            $url = $this->__CreateOauthUrlForCode($baseUrl);
            $res=doCurl($url);
            Header("Location: $url");
            exit();
        }
    }
    public function GetOpenid($code=false)
    {
        //获取code码，以获取openid
        $openid = $this->getOpenidFromMp($code);
        return $openid;
    }
    private function __CreateOauthUrlForCode($redirectUrl)
    {
        $urlObj["appid"] = config('wechat')['official_account']['default']['app_id'];//'wx5ae58843cfe3fcd4';
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
        $urlObj["scope"] = "snsapi_base";
        $urlObj["state"] = "STATE"."#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
    }

    public function GetOpenidFromMp($code)
    {
        $url = $this->__CreateOauthUrlForOpenid($code);
        $res=doCurl($url);
        //取出openid
        $data = json_decode($res,true);
        $this->data = $data;
        $openid = $data['openid'];
        return $openid;
    }

    private function ToUrlParams($urlObj)
    {
        $buff = "";
        foreach ($urlObj as $k => $v)
        {
            if($k != "sign"){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    private function __CreateOauthUrlForOpenid($code)
    {
        $urlObj["appid"]  =config('wechat')['official_account']['default']['app_id'];//'wx5ae58843cfe3fcd4';
        $urlObj["secret"] =config('wechat')['official_account']['default']['secret'];//'fa73be46b75e6279be8166b7d15bfc8f';
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
    }

}

